#include "setting.h"
#include "ui_setting.h"
#include "mainwindow.h"
#include "switchbutton.h"
#include <QDebug>
#include <QThread>
#include <QScrollBar>
#include <QTimer>
#include <QDateTime>

Setting::Setting(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    SerialPort = new QSerialPort(this);
    init();
    connect(ui->widget_button_red, &SwitchButton::statusChanged, this, &Setting::switchButton_R);//红灯的状态
    connect(ui->widget_button_green, &SwitchButton::statusChanged, this, &Setting::switchButton_G);//绿灯的状态
    connect(ui->widget_button_blue, &SwitchButton::statusChanged, this, &Setting::switchButton_B);//蓝灯的状态
    connect(ui->widget_button_beep, &SwitchButton::statusChanged, this, &Setting::switchButton_BEEP);//beep的状态
    connect(ui->widget_button_engin, &SwitchButton::statusChanged, this, &Setting::switchButton_E);//舵机的状态

    QTimer *timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&Setting::on_btn_reflash_clicked);
    timer->start(5000);

    QTimer *timer2 = new QTimer(this);
    connect(timer2,&QTimer::timeout,this,&Setting::renewTimer);
    timer2->start(1000);
}

Setting::~Setting()
{
    delete ui;
}

QSerialPort *Setting::getSerialPort()
{
    qDebug()<<"hello1";
    return SerialPort;
}

//打开串口
void Setting::on_btn_open_clicked()
{
    SerialPort->setPortName(ui->comboBox_portname->currentText());
    SerialPort->open(QIODevice::ReadWrite);//以只写方法打开串口

    if(SerialPort->isOpen())
    {
        SerialPort->setBaudRate(ui->comboBox_portBod->currentText().toInt());
        ui->label_text->setText("打开串口成功 \n串口号：" + ui->comboBox_portname->currentText());
        connect(SerialPort,&QSerialPort::readyRead,this,&Setting::messlot);
    }
    else
    {
        ui->label_text->setText("打开串口失败！！！");
        return;
    }
}

//关闭串口
void Setting::on_btn_close_clicked()
{
    SerialPort->close();
    //判断串口是否打开
    if(SerialPort->isOpen())
    {
         ui->label_text->setText("串口关闭失败！！！");
    }else
    {
        ui->label_text->setText("串口已关闭");
    }
}

//刷新串口
void Setting::on_btn_reflesh_clicked()
{
    ui->comboBox_portname->clear();
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        ui->comboBox_portname->addItem(info.portName());
    }
    if(ui->comboBox_portname->currentIndex() == -1)
    {
        QMessageBox::information(this,"提示","刷新失败！\n当前没有端口！");
    }
    else
    {
        QMessageBox::information(this,"提示","刷新成功！");
    }
}

//发送消息
void Setting::on_btn_send_clicked()
{
    QString sendData = ui->plainTextEdit_send->toPlainText();
    sendData.append("\r\n");
    QByteArray sendDataArray = sendData.toUtf8();
    SerialPort->write(sendDataArray);
    ui->plainTextEdit_send->clear();
}

//清空消息
void Setting::on_btn_receive_clicked()
{
    ui->plainTextEdit_receive->clear();
}

//串口接收信息的处理函数
void Setting::messlot()
{
    QByteArray array = SerialPort->readAll();
    // 转换编码为gbk
    QTextCodec *codec = QTextCodec::codecForName("gbk"); // 确保这里设置为gbk编码
    QString str = codec->toUnicode(array);
    QStringList strlist = str.split(",");

    // 验证数据长度
    if (strlist.count() >= 3) {
        // 提取温度、湿度和人体红外信号的值
        data.temp = strlist.at(0).toInt();
        data.humi = strlist.at(1).toInt();
        data.light_strong = strlist.at(2).toInt();

        // 将接收到的信息传送到文本框
        ui->plainTextEdit_receive->insertPlainText(str);
        Log_Text_Display("当前温度:" + strlist.at(0) + '\n');
        Log_Text_Display("当前湿度:" + strlist.at(1) + '\n');
        Log_Text_Display("当前光照强度：" + strlist.at(2) + '\n');

//        QThread::sleep(2);
        // 显示在LCDNumber上
        ui->lcdNumber_temp->display(data.temp);
        ui->lcdNumber_humi->display(data.humi);
        ui->lcdNumber_lux->display(data.light_strong);
    } else {

    }
}


//初始化
void Setting::init()
{
    connect(ui->widget_button_red, &SwitchButton::statusChanged, [=](bool checked){
        if(checked)
        {
            Log_Text_Display("红灯已打开！\n");
        }
        else
        {
            Log_Text_Display("红灯已关闭！\n");
        }
    });
    connect(ui->widget_button_green, &SwitchButton::statusChanged, this, [=](bool checked){
        if(checked)
        {
            Log_Text_Display("绿灯已打开！\n");
        }
        else
        {
            Log_Text_Display("绿灯已关闭！\n");
        }
    });
    connect(ui->widget_button_blue, &SwitchButton::statusChanged, this, [=](bool checked){
        if(checked)
        {
            Log_Text_Display("蓝灯已打开！\n");
        }
        else
        {
            Log_Text_Display("蓝灯已关闭！\n");
        }
    });
    connect(ui->widget_button_beep, &SwitchButton::statusChanged, this, [=](bool checked){
        if(checked)
        {
            Log_Text_Display("蜂鸣器已打开！\n");
        }
        else
        {
            Log_Text_Display("蜂鸣器已关闭！\n");
        }
    });

    connect(ui->widget_button_engin, &SwitchButton::statusChanged, this, [=](bool checked){
        if(checked)
        {
            Log_Text_Display("舵机已打开！\n");
        }
        else
        {
            Log_Text_Display("舵机已关闭！\n");
        }
    });
    ui->label_text->clear();

    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        ui->comboBox_portname->addItem(info.portName());
    }

    //显示波特率
    QStringList baudList;//波特率
    baudList<<"9600"<<"14400"<<"19200"
           <<"38400"<<"56000"<<"57600"<<"115200";
    ui->comboBox_portBod->addItems(baudList);
}

void Setting::on_btn_setting_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void Setting::on_btn_back_clicked()
{
    ui->stackedWidget->setCurrentIndex(1);
}

void Setting::renewTimer()
{
    // 获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();
    // 格式化时间
    QString timeString = currentTime.toString("yyyy-MM-dd hh:mm:ss");

    ui->label_CurrentTime->setText(timeString);
}

/*日志显示*/
void Setting::Log_Text_Display(QString text)
{
    QPlainTextEdit *plainTextEdit_log=ui->plainTextEdit_showInfo;

    //设置只读
    if(!plainTextEdit_log->isReadOnly())
    {
        plainTextEdit_log->setReadOnly(true);
    }

    //设置光标到文本末尾
    plainTextEdit_log->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
    //当文本数量超出一定范围就清除
    if(plainTextEdit_log->toPlainText().size()>1024*4)
    {
        plainTextEdit_log->clear();
    }
    plainTextEdit_log->insertPlainText(text);
    //移动滚动条到底部
    QScrollBar *scrollbar = plainTextEdit_log->verticalScrollBar();
    if(scrollbar)
    {
        scrollbar->setSliderPosition(scrollbar->maximum());
    }
}

//红灯
void Setting::switchButton_R(bool checked)
{
    if(checked == true)
    {
        ui->LED_R->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/redLED.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
        if(SerialPort->isOpen())
        {
            QString sendData_red_on = "0";
            sendData_red_on.append("\r\n");
            QByteArray sendDataArray_red_on = sendData_red_on.toUtf8();
            SerialPort->write(sendDataArray_red_on);
        }
    }
    else
    {
        ui->LED_R->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/blackLED.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
        if(SerialPort->isOpen())
        {
            QString sendData_red_off = "1";
            sendData_red_off.append("\r\n");
            QByteArray sendDataArray_2 = sendData_red_off.toUtf8();
            SerialPort->write(sendDataArray_2);
        }
    }
}

//绿灯
void Setting::switchButton_G(bool checked)
{
    if(checked == true)
    {

        ui->LED_G->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/greenLED.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
        if(SerialPort->isOpen())
        {
            QString sendData_green_on = "2";
            sendData_green_on.append("\r\n");
            QByteArray sendDataArray_green_on = sendData_green_on.toUtf8();
            SerialPort->write(sendDataArray_green_on);
        }
    }
    else
    {
        ui->LED_G->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/blackLED.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
        if(SerialPort->isOpen())
        {
            QString sendData_green_off = "3";
            sendData_green_off.append("\r\n");
            QByteArray sendDataArray_green_off = sendData_green_off.toUtf8();
            SerialPort->write(sendDataArray_green_off);
        }
    }
}

//蓝灯
void Setting::switchButton_B(bool checked)
{
    if(checked == true)
    {
        ui->LED_B->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/blueLED.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
        if(SerialPort->isOpen())
        {
            QString sendData_blue_on = "4";
            sendData_blue_on.append("\r\n");
            QByteArray sendDataArray_blue_on = sendData_blue_on.toUtf8();
            SerialPort->write(sendDataArray_blue_on);
        }
    }
    else
    {
        ui->LED_B->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/blackLED.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
        if(SerialPort->isOpen())
        {
            QString sendData_blue_off = "5";
            sendData_blue_off.append("\r\n");
            QByteArray sendDataArray_green_off = sendData_blue_off.toUtf8();
            SerialPort->write(sendDataArray_green_off);
        }
    }
}
//蜂鸣器
void Setting::switchButton_BEEP(bool checked)
{
    if(checked == true)
    {
        ui->BEEP_label->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/beep_ON.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
        if(SerialPort->isOpen())
        {
            QString sendData_beep_on = "6";
            sendData_beep_on.append("\r\n");
            QByteArray sendDataArray_beep_on = sendData_beep_on.toUtf8();
            SerialPort->write(sendDataArray_beep_on);
        }
    }
    else
    {
        ui->BEEP_label->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/beep_OFF.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
        if(SerialPort->isOpen())
        {
            QString sendData_beep_off = "7";
            sendData_beep_off.append("\r\n");
            QByteArray sendDataArray_beep_off = sendData_beep_off.toUtf8();
            SerialPort->write(sendDataArray_beep_off);
        }
    }
}

void Setting::switchButton_P(bool checked)
{
    qDebug()<<checked;
}

void Setting::switchButton_E(bool checked)
{
    if(checked == true)
    {

        ui->Engine_label->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/engine _ON.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
    }
    else
    {
        ui->Engine_label->setStyleSheet("QLabel{"
                                       "background-image:url(:/res/engine_OFF.png);"
                                       "background-position:top right;"
                                       "background-origin:content;"
                                       "background-repeat:none;"
                                       "}");
    }
}

void Setting::on_btn_reflash_clicked()
{
    QString sendData_red_on = "10";
    sendData_red_on.append("\r\n");
    QByteArray sendDataArray_red_on = sendData_red_on.toUtf8();
    SerialPort->write(sendDataArray_red_on);
}
